package jinyilw.swing.rlaf.ui;

import jinyilw.swing.ComponentTools;
import jinyilw.swing.graphics.RenderingConfig;
import jinyilw.swing.rlaf.UITools;
import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.JInternalFrame;
import javax.swing.border.Border;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;

/**
 * @author Jinyi
 */
public class RInternalFrameBorder implements Border
{
	private static final AlphaComposite alphaComposite = ComponentTools.alphaComposite;
	private int shadowSize = 3;
	private int innerSpace = 0;
	private final int arc = 5;
	private final Color shadowColor = new Color(0, 16, 0);
	private final float shadowAlpha = 0.5f;
	private final Insets borderInsets;
	private final RenderingConfig renderingConfig = new RenderingConfig();

	public RInternalFrameBorder()
	{
		this(3, 0);
	}

	public RInternalFrameBorder(int aShadowSize, int aInnerSpace)
	{
		shadowSize = aShadowSize;
		innerSpace = aInnerSpace;
		int frameWidth = 2 + innerSpace;
		borderInsets = new Insets(frameWidth, frameWidth,
				frameWidth + shadowSize, frameWidth + shadowSize);
	}

	@Override
	public void paintBorder(Component c, Graphics g, int x, int y, int w, int h)
	{
		Graphics2D g2d = (Graphics2D) g;
		Composite saveComposite = g2d.getComposite();
		renderingConfig.setAAPainting(g2d);
		if (shadowSize > 0)
		{
			g2d.setColor(shadowColor);
			float alpha = shadowAlpha;
			int x1 = x + w - shadowSize, y1 = y + h - shadowSize;
			int xx = x + shadowSize + 2, yy = y + shadowSize + 4;
			for (int i = 0; i < shadowSize; i++)
			{
				g2d.setComposite(alphaComposite.derive(alpha));
				g2d.drawLine(x1 + i, yy, x1 + i, y1 - arc + 2);
				g2d.drawLine(xx, y1 + i, x1 - arc + 2, y1 + i);
				g2d.drawArc(x1 - arc, y1 - arc, arc + i, arc + i, 0, -90);
				alpha -= (alpha / 2);
			}
			g2d.setComposite(alphaComposite.derive(shadowAlpha / 2));
			g2d.drawArc(x1 - arc, y1 - arc - 1, arc, arc, 0, -90);
			g2d.drawArc(x1 - arc - 1, y1 - arc, arc, arc, 0, -90);

		}
		if (UITools.isLight())
			g2d.setColor(Color.white);
		else
			g2d.setColor(RThemeColor.colorSet.borderColor);

		if (c instanceof JInternalFrame)
			if (((JInternalFrame) c).isSelected())
				g2d.setColor(RThemeColor.windowBorderColor);

		g2d.setComposite(alphaComposite.derive(0.8f));
		g2d.drawRoundRect(x + 1, y + 1, w - shadowSize - 2, h - shadowSize - 2,
				arc, arc);
		g2d.setComposite(alphaComposite.derive(0.4f));
		int xx = x + w - shadowSize - 2, yy = y + h - shadowSize - 2;
		g2d.drawLine(xx, y + 1, xx, yy);
		g2d.drawLine(x + 1, yy, xx, yy);
		renderingConfig.resetAAPainting(g2d);
		g2d.setComposite(saveComposite);
	}

	@Override
	public Insets getBorderInsets(Component c)
	{
		if (borderInsets != null)
			return borderInsets;
		return new Insets(0, 0, 0, 0);
	}

	@Override
	public boolean isBorderOpaque()
	{
		return false;
	}
}
